//window串口驱动

#include "Window_Serial.h"
#include <stdint.h>
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <stdlib.h>

HANDLE Serial;//串口句柄
#define Debug_Serial 1
uint8_t Debug_Flag;


void Windows_Serial_Init(void)
{
    //打开串口
    Serial = CreateFile("COM2",//COM3口
        GENERIC_READ | GENERIC_WRITE,//允许读和写
        0,//独占方式
        NULL,
        OPEN_EXISTING,//打开而不是创建
        0,//同步方式
        //FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERAPPLE,//重叠方式
        NULL);
    if(Serial == (HANDLE)-1)
    {
        MessageBox(NULL,"Open Serial Fail!!!","Error",1);
        return 0;
    }
    SetupComm(Serial, 20480, 20480);//输入缓冲区和输出缓冲区的大小都是20480
    
    COMMTIMEOUTS TimeOuts;    
    TimeOuts.ReadIntervalTimeout = 1000;//设定读超时
    TimeOuts.ReadTotalTimeoutMultiplier = 500;
    TimeOuts.ReadTotalTimeoutConstant = 5000;    
    TimeOuts.WriteTotalTimeoutMultiplier = 500;//设定写超时
    TimeOuts.WriteTotalTimeoutConstant = 2000;
    SetCommTimeouts(Serial, &TimeOuts);//设置超时
    
    DCB dcb;
    GetCommState(Serial, &dcb);
    dcb.BaudRate = 115200;//波特率为115200
    dcb.ByteSize = 8;//每个字节有8位
    dcb.Parity = NOPARITY;//无奇偶校验位
    dcb.StopBits = ONESTOPBIT;//一个停止位
    dcb.fParity = FALSE;
    dcb.fNull = FALSE;
    SetCommState(Serial, &dcb);
    PurgeComm(Serial, PURGE_TXCLEAR|PURGE_RXCLEAR);//在读写串口之前清空缓冲区
}
 
 /*
//输出到屏幕的指令方法
void Serial_Write_16bit(uint16_t length,...)
{
    //同步写串口
    DWORD dwWriteLen = 0;

    uint32_t i;
    va_list vaList;
    uint8_t cmd[255] = {0x5A,0xA5,0x1,0x82};

    if(length <= 3) return;
    va_start(vaList,length);
    cmd[2] += length;
    cmd[4] = va_arg(vaList,int);
    cmd[5] = va_arg(vaList,int);
    length -= 2;
    for (i = 0; i < length; i++)
    {
        cmd[i + 6] = va_arg(vaList,int);
    }
    va_end(vaList);

#if Debug_Serial
    //Print Uart Tx of dataes
    printf("Serial Write Data of length: %d\n\t",(cmd[2] + 3));
    for (i = 0; i < (cmd[2] + 3); i++)
    {
        printf("%02X ",cmd[i]);
    }
    printf("\n");
#endif

    if(!WriteFile(Serial, cmd, cmd[2] + 3, &dwWriteLen, NULL))
    {
        MessageBox(NULL,"Write Serial Fail!!!","Error",1);
    }
}
*/

void Serial_Tx(uint8_t array[],uint16_t length)
{
    //同步写串口
    DWORD dwWriteLen = 0;
    
#if Debug_Serial
    uint16_t i;

    if(Debug_Flag > 0)
    {
        //Print Uart Tx of dataes
        printf("Serial Write Data of length: %d\n\t",length);
        for (i = 0; i < length; i++)
        {
            printf("%02X ",array[i]);
        }
        printf("\n");
    }
#endif

    if(!WriteFile(Serial, array, length, &dwWriteLen, NULL))
    {
        MessageBox(NULL,"Write Serial Fail!!!","Error",1);
    }
}
void Serial_Tx_Chars(char* txt,uint32_t len)
{
    //同步写串口
    DWORD dwWriteLen = 0;
    
    if(!WriteFile(Serial, txt, len, &dwWriteLen, NULL))
    {
        MessageBox(NULL,"Write Serial Fail!!!","Error",1);
    } 
}

void Serial_Close(void)
{
    CloseHandle(Serial);
}
